<template>
  <el-container style="width: 100%; height: 100%">
    <!-- 头部标题 -->
    <el-header class="header"> 轨道控制器 </el-header>
    <!-- 主要内容区域，包含 Three.js 画布 -->
    <el-main class="canvas-container">
      <canvas ref="canvas" class="canvas"></canvas>
    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

// Three.js 相关变量声明
// 场景
let scene: THREE.Scene
// 透视相机
let camera: THREE.PerspectiveCamera
// WebGL渲染器
let renderer: THREE.WebGLRenderer
// 动画帧ID
let animationFrameId: number
// 轨道控制器
let controls: InstanceType<typeof OrbitControls>
// 画布引用
const canvas = ref<HTMLCanvasElement>()
// 点光源
let pointLight: THREE.PointLight
const angle = ref(0)

// 组件挂载时初始化场景并开始动画
onMounted(() => {
  initScene()
  animate()
  // 添加窗口大小改变事件监听
  window.addEventListener('resize', onWindowResize)
})

// 初始化场景
function initScene() {
  if (!canvas.value) return

  // 获取画布尺寸
  const width = canvas.value.clientWidth
  const height = canvas.value.clientHeight
  console.log(width, height)

  // 创建场景
  scene = new THREE.Scene()

  // 创建透视相机
  camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000)

  // 创建WebGL渲染器
  renderer = new THREE.WebGLRenderer({ canvas: canvas.value, antialias: true })
  renderer.setSize(width, height)
  renderer.shadowMap.enabled = true
  // 设置设备像素比，确保在高分辨率屏幕上清晰显示
  renderer.setPixelRatio(window.devicePixelRatio)

  // 设置相机位置
  camera.position.set(2, 100, 18)
  camera.lookAt(0, 0, 0)

  // 初始化轨道控制器
  //它的作用是控制相机，让相机可以自由的旋转，缩放，平移
  controls = new OrbitControls(camera, renderer.domElement)

  const plane = new THREE.Mesh(
    new THREE.PlaneGeometry(100, 100),
    new THREE.MeshStandardMaterial({ color: 0x999999 }),
  )
  plane.rotation.x = -Math.PI / 2
  plane.receiveShadow = true
  scene.add(plane)

  // 创建立方体
  const cube = new THREE.Mesh(
    new THREE.BoxGeometry(10, 10, 10),
    new THREE.MeshStandardMaterial({ color: 0xff11ff }),
  )
  cube.position.set(0, 5, 0)
  cube.castShadow = true
  scene.add(cube)

  const directionalLight = new THREE.DirectionalLight(0xffffff, 10)
  directionalLight.position.set(100, 20, 0)
  directionalLight.castShadow = true
  // directionalLight.shadow.mapSize.set(2048, 2048)
  const directionalLightHelper = new THREE.DirectionalLightHelper(directionalLight, 1)
  scene.add(directionalLight, directionalLightHelper)

  pointLight = new THREE.PointLight(0xffffff, 500, 1000)
  pointLight.position.set(10, 10, 0)
  pointLight.castShadow = true
  const pointLightHelper = new THREE.PointLightHelper(pointLight, 1)
  scene.add(pointLight, pointLightHelper)
}

// 动画循环函数
function animate() {
  angle.value += 0.01
  pointLight.position.x = Math.cos(angle.value) * 10
  pointLight.position.z = Math.sin(angle.value) * 10
  animationFrameId = requestAnimationFrame(animate)
  // 更新控制器
  controls.update()
  // 渲染场景
  renderer.render(scene, camera)
}

// 清理函数
function cleanup() {
  // 取消动画帧
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
  }

  // 清理轨道控制器
  if (controls) {
    controls.dispose()
  }

  // 清理渲染器
  if (renderer) {
    // 移除所有事件监听器
    renderer.domElement.removeEventListener('resize', onWindowResize)
    // 释放渲染器资源
    renderer.dispose()
    // 清空渲染器
    renderer.forceContextLoss()
    // 移除画布
    renderer.domElement.remove()
  }

  // 清理场景
  if (scene) {
    // 遍历场景中的所有对象
    scene.traverse((object) => {
      if (object instanceof THREE.Mesh) {
        // 释放几何体资源
        object.geometry.dispose()
        // 释放材质资源
        if (Array.isArray(object.material)) {
          object.material.forEach((material) => material.dispose())
        } else {
          object.material.dispose()
        }
      }
      if (object instanceof THREE.Light) {
        object.dispose()
      }
      if (
        object instanceof THREE.DirectionalLightHelper ||
        object instanceof THREE.PointLightHelper ||
        object instanceof THREE.SpotLightHelper
      ) {
        object.dispose()
      }
    })
    // 清空场景
    scene.clear()
  }

  // 清理相机
  if (camera) {
    camera.clear()
  }
}

// 窗口大小改变时的处理函数
function onWindowResize() {
  if (!canvas.value) return
  const width = canvas.value.clientWidth
  const height = canvas.value.clientHeight

  // 更新相机
  camera.aspect = width / height
  camera.updateProjectionMatrix()

  // 更新渲染器
  renderer.setSize(width, height)
}

// 组件卸载时清理资源
onUnmounted(() => {
  cleanup()
  // 移除窗口大小改变事件监听
  window.removeEventListener('resize', onWindowResize)
})
</script>

<style scoped>
/* 头部样式 */
.header {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

/* 画布容器样式 */
.canvas-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

/* 画布样式   // 保持画布比例*/
.canvas {
  width: 100%;
  height: 100%;
  display: block;
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
</style>
